import { createConnection } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { config } from 'dotenv';
import { faker } from '@faker-js/faker/locale/zh_CN'; // 使用中文数据

config();

async function checkTableStructure(connection) {
  console.log('检查活动表结构...');
  try {
    const activityColumns = await connection.query('DESCRIBE activities');
    console.log('活动表列:', activityColumns.map(col => col.Field).join(', '));
    return activityColumns.map(col => col.Field);
  } catch (error) {
    console.error('检查表结构时出错:', error);
    return [];
  }
}

async function checkEnumValues(connection) {
  try {
    // 检查 feeMode 列的枚举值
    const feeModeEnum = await connection.query(`
      SELECT COLUMN_TYPE 
      FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_NAME = 'activities' AND COLUMN_NAME = 'feeMode'
    `);
    
    if (feeModeEnum && feeModeEnum.length > 0) {
      const enumValues = feeModeEnum[0].COLUMN_TYPE
        .replace('enum(', '')
        .replace(')', '')
        .split(',')
        .map(val => val.trim().replace(/'/g, ''));
      
      console.log('数据库中 feeMode 的枚举值:', enumValues.join(', '));
      return enumValues;
    }
  } catch (error) {
    console.error('检查枚举值时出错:', error);
  }
  return null;
}

async function addTestData() {
  console.log('开始添加测试数据...');
  
  const connection = await createConnection({
    name: 'testDataConnection',
    type: 'mysql',
    host: process.env.DB_HOST || 'localhost',
    port: Number(process.env.DB_PORT) || 3306,
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '123456',
    database: process.env.DB_DATABASE || 'hdq-news',
    synchronize: false
  });

  try {
    // 检查表结构
    const columns = await checkTableStructure(connection);
    
    // 生成默认密码的哈希值 (默认密码: '123456')
    const salt = await bcrypt.genSalt();
    const defaultPasswordHash = await bcrypt.hash('123456', salt);
    
    // 添加用户数据
    console.log('添加用户数据...');
    
    // 检查是否已有数据
    const existingUsers = await connection.query('SELECT COUNT(*) as count FROM users');
    const userCount = existingUsers[0].count;
    console.log(`当前已有 ${userCount} 个用户`);
    
    // 添加50个用户
    for (let i = 0; i < 50; i++) {
      const gender = Math.random() > 0.5 ? 1 : 2; // 1-男性, 2-女性
      const firstName = gender === 1 ? faker.person.firstName('male') : faker.person.firstName('female');
      const lastName = faker.person.lastName();
      const nickname = `${lastName}${firstName}`;
      
      // 生成手机号
      const phone = `1${faker.helpers.arrayElement(['3', '5', '7', '8', '9'])}${faker.string.numeric(9)}`;
      
      // 生成用户名
      const username = faker.internet.userName({ firstName, lastName }).toLowerCase();
      
      // 生成邮箱
      const email = faker.internet.email({ firstName, lastName }).toLowerCase();
      
      // 生成头像
      const avatar = `https://randomuser.me/api/portraits/${gender === 1 ? 'men' : 'women'}/${i % 100}.jpg`;
      
      // 生成生日
      const birthday = faker.date.between({ from: '1970-01-01', to: '2000-12-31' });
      
      // 生成地址
      const province = faker.location.state();
      const city = faker.location.city();
      
      // 生成简介
      const bio = faker.lorem.paragraph();
      
      try {
        await connection.query(`
          INSERT INTO users (
            username, nickname, phone, password, avatar, email, bio, gender, 
            birthday, province, city, status, isPhoneVerified, isEmailVerified, 
            createdAt, updatedAt
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        `, [
          username, nickname, phone, defaultPasswordHash, avatar, email, bio, gender,
          birthday, province, city, 1, true, true
        ]);
        
        console.log(`已添加用户 ${i + 1}: ${nickname}`);
      } catch (error) {
        console.error(`添加用户 ${i + 1} 失败:`, error.message);
        // 继续添加下一个用户
      }
    }
    
    // 获取所有用户ID
    const userIds = await connection.query('SELECT id FROM users');
    if (!userIds || userIds.length === 0) {
      console.error('没有找到用户数据，请先添加用户');
      return;
    }
    const userIdList = userIds.map(user => user.id);
    console.log(`找到 ${userIdList.length} 个用户ID`);
    
    // 活动类型
    const activityTypes = ['徒步', '骑行', '露营', '摄影', '登山', '城市探索', '文化体验', '美食之旅', '志愿服务', '户外运动'];
    
    // 活动状态
    const activityStatuses = ['DRAFT', 'RECRUITING', 'ONGOING', 'COMPLETED', 'CANCELLED'];
    
    // 费用模式
    const feeModes = ['FREE', 'PAID', 'DEPOSIT']; // 移除 'AA'，添加 'DEPOSIT'
    
    // 难度级别
    const difficultyLevels = ['EASY', 'MEDIUM', 'HARD']; // 修改为与枚举定义匹配的值
    
    // 检查枚举值
    const feeModeEnumValues = await checkEnumValues(connection);
    if (feeModeEnumValues) {
      // 使用数据库中的枚举值
      feeModes.length = 0;
      feeModeEnumValues.forEach(val => feeModes.push(val));
    }
    
    // 添加活动数据
    console.log('添加活动数据...');
    
    // 检查是否已有数据
    const existingActivities = await connection.query('SELECT COUNT(*) as count FROM activities');
    const activityCount = existingActivities[0].count;
    console.log(`当前已有 ${activityCount} 个活动`);
    
    // 添加50个活动
    for (let i = 0; i < 50; i++) {
      try {
        // 随机选择一个用户作为创建者
        const creatorId = faker.helpers.arrayElement(userIdList);
        
        // 生成活动标题
        const activityType = faker.helpers.arrayElement(activityTypes);
        const title = `${activityType}活动: ${faker.location.city()}${faker.word.adjective()}之旅`;
        
        // 生成活动描述
        const description = faker.lorem.paragraphs(3);
        
        // 生成活动地点
        const location = faker.location.city();
        const address = faker.location.streetAddress(true);
        
        // 生成活动时间
        const startTime = faker.date.future();
        const endTime = new Date(startTime.getTime() + faker.number.int({ min: 3600000, max: 86400000 * 3 }));
        
        // 生成路线信息
        const routeDistance = faker.number.float({ min: 1, max: 50, fractionDigits: 1 });
        const routeDescription = faker.lorem.paragraph();
        
        // 生成参与人数
        const maxParticipants = faker.number.int({ min: 5, max: 100 });
        const minParticipants = faker.number.int({ min: 1, max: maxParticipants - 1 });
        const currentParticipants = faker.number.int({ min: 0, max: maxParticipants });
        
        // 生成费用信息
        const feeMode = faker.helpers.arrayElement(feeModes);
        const feeAmount = feeMode === 'FREE' ? 0 : faker.number.float({ min: 10, max: 500, fractionDigits: 2 });
        const depositAmount = feeMode === 'FREE' ? 0 : faker.number.float({ min: 0, max: 200, fractionDigits: 2 });
        const feeDescription = feeMode === 'FREE' ? '免费活动' : `费用包含: ${faker.lorem.sentence()}`;
        
        // 生成难度级别
        const difficultyLevel = faker.helpers.arrayElement(difficultyLevels);
        
        // 生成要求和装备
        const requirements = faker.lorem.paragraph();
        const equipmentRequired = faker.lorem.paragraph();
        
        // 生成统计数据
        const viewCount = faker.number.int({ min: 0, max: 1000 });
        const favoriteCount = faker.number.int({ min: 0, max: 100 });
        const commentCount = faker.number.int({ min: 0, max: 50 });
        
        // 生成封面图
        const cover = `https://picsum.photos/800/600?random=${i}`;
        
        // 生成标签
        const tag = faker.helpers.arrayElement(activityTypes);
        
        // 生成状态
        const status = faker.helpers.arrayElement(activityStatuses);
        
        // 构建字段和值
        let fields = [
          'title', 'description', 'location', 'address', 'startTime', 'endTime',
          'routeDistance', 'routeDescription', 'maxParticipants', 'minParticipants',
          'currentParticipants', 'feeMode', 'feeAmount', 'depositAmount', 'feeDescription',
          'difficultyLevel', 'requirements', 'equipmentRequired',
          'cover', 'tag', 'creatorId', 'status', 'createdAt', 'updatedAt'
        ];
        
        let values = [
          title, description, location, address, startTime, endTime,
          routeDistance, routeDescription, maxParticipants, minParticipants,
          currentParticipants, feeMode, feeAmount, depositAmount, feeDescription,
          difficultyLevel, requirements, equipmentRequired,
          cover, tag, creatorId, status, new Date(), new Date()
        ];
        
        // 检查是否有 view_count 列
        if (columns.includes('view_count')) {
          fields.push('view_count');
          values.push(viewCount);
        }
        
        // 检查是否有 favorite_count 列
        if (columns.includes('favorite_count')) {
          fields.push('favorite_count');
          values.push(favoriteCount);
        }
        
        // 检查是否有 comment_count 列
        if (columns.includes('comment_count')) {
          fields.push('comment_count');
          values.push(commentCount);
        }
        
        // 构建占位符
        const placeholders = fields.map(() => '?').join(', ');
        
        // 执行 SQL
        const sql = `
          INSERT INTO activities (${fields.join(', ')})
          VALUES (${placeholders})
        `;
        
        await connection.query(sql, values);
        
        console.log(`已添加活动 ${i + 1}: ${title}`);
      } catch (error) {
        console.error(`添加活动 ${i + 1} 失败:`, error);
        // 打印更详细的错误信息
        if (error.sql) {
          console.error('SQL:', error.sql);
        }
        if (error.parameters) {
          console.error('参数:', error.parameters);
        }
        // 继续添加下一个活动
      }
    }
    
    console.log('测试数据添加完成');
  } catch (error) {
    console.error('添加测试数据时出错:', error);
  } finally {
    await connection.close();
  }
}

// 添加一个简化版本的函数，只添加活动数据
async function addActivitiesOnly() {
  console.log('开始添加活动数据...');
  
  const connection = await createConnection({
    name: 'testDataConnection',
    type: 'mysql',
    host: process.env.DB_HOST || 'localhost',
    port: Number(process.env.DB_PORT) || 3306,
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '123456',
    database: process.env.DB_DATABASE || 'hdq-news',
    synchronize: false
  });

  try {
    // 检查表结构
    const columns = await checkTableStructure(connection);
    
    // 检查枚举值
    const feeModeEnumValues = await checkEnumValues(connection);
    if (feeModeEnumValues) {
      // 使用数据库中的枚举值
      const feeModes = feeModeEnumValues;
      
      // 获取所有用户ID
      const userIds = await connection.query('SELECT id FROM users');
      if (!userIds || userIds.length === 0) {
        console.error('没有找到用户数据，请先添加用户');
        return;
      }
      const userIdList = userIds.map(user => user.id);
      
      // 添加10个简化的活动
      for (let i = 0; i < 10; i++) {
        try {
          const creatorId = userIdList[0]; // 使用第一个用户作为创建者
          const title = `测试活动 ${i + 1}`;
          const description = '这是一个测试活动';
          const location = '测试地点';
          const address = '测试地址';
          const startTime = new Date(Date.now() + 86400000); // 明天
          const endTime = new Date(Date.now() + 172800000); // 后天
          
          // 使用第一个枚举值作为默认值，确保它是有效的
          const feeMode = feeModes[0];
          
          // 根据实际表结构构建 SQL 语句
          let fields = [
            'title', 'description', 'location', 'address', 'startTime', 'endTime',
            'maxParticipants', 'minParticipants', 'currentParticipants',
            'feeMode', // 添加 feeMode 字段
            'creatorId', 'status', 'createdAt', 'updatedAt'
          ];
          
          // 检查是否有 view_count 列
          if (columns.includes('view_count')) {
            fields.push('view_count');
          }
          
          // 检查是否有 favorite_count 列
          if (columns.includes('favorite_count')) {
            fields.push('favorite_count');
          }
          
          // 检查是否有 comment_count 列
          if (columns.includes('comment_count')) {
            fields.push('comment_count');
          }
          
          // 构建占位符
          const placeholders = fields.map(() => '?').join(', ');
          
          // 构建值数组
          const values = [
            title, description, location, address, startTime, endTime,
            10, 1, 0, 
            feeMode, // 添加 feeMode 值
            creatorId, 'RECRUITING', new Date(), new Date()
          ];
          
          // 添加额外的值
          if (columns.includes('view_count')) {
            values.push(0);
          }
          if (columns.includes('favorite_count')) {
            values.push(0);
          }
          if (columns.includes('comment_count')) {
            values.push(0);
          }
          
          // 执行 SQL
          const sql = `
            INSERT INTO activities (${fields.join(', ')})
            VALUES (${placeholders})
          `;
          
          console.log(`执行 SQL: ${sql}`);
          console.log(`值: ${values.join(', ')}`);
          
          await connection.query(sql, values);
          
          console.log(`已添加简化活动 ${i + 1}: ${title}`);
        } catch (error) {
          console.error(`添加简化活动 ${i + 1} 失败:`, error);
        }
      }
      
      console.log('简化活动数据添加完成');
    } else {
      console.error('无法获取 feeMode 枚举值，请检查数据库结构');
    }
  } catch (error) {
    console.error('添加活动数据时出错:', error);
  } finally {
    await connection.close();
  }
}

// 根据命令行参数决定运行哪个函数
const args = process.argv.slice(2);
if (args.includes('--activities-only')) {
  addActivitiesOnly()
    .then(() => process.exit(0))
    .catch(error => {
      console.error(error);
      process.exit(1);
    });
} else {
  addTestData()
    .then(() => process.exit(0))
    .catch(error => {
      console.error(error);
      process.exit(1);
    });
}




